import { Form, Input, InputNumber, Select } from 'antd';
import { type CSSProperties, useEffect, useState } from 'react';
import { type ComponentSetter, useComponentConfigStore } from '../../../store/component-config';
import { useComponetsStore } from '../../../store/components';
import CssEditor from '../CSSEditor';
import { debounce } from 'lodash-es';

// CSS字符串转换为对象
function styleToObject(cssText: string, callback: (name: string, value: string) => void) {
  const regex = /([\w-]+)\s*:\s*([^;]+)/g;
  let match;
  while ((match = regex.exec(cssText))) {
    const name = match[1].trim();
    const value = match[2].trim();
    callback(name, value);
  }
}

export function ComponentStyle() {//设置组件样式
  const [form] = Form.useForm();
  const [css, setCss] = useState<string>(`.comp{\n\n}`);

  const { curComponentId, curComponent, updateComponentStyles } = useComponetsStore();
  const { componentConfig } = useComponentConfigStore();

  useEffect(() => {
    form.resetFields();//选中另一个组件的时候，css表单没有清空，reset一下

    const data = form.getFieldsValue();
    form.setFieldsValue({ ...data, ...curComponent?.styles });
    
    setCss(toCSSStr(curComponent?.styles!))

    // if (curComponent?.styles) {
    //   setCss(toCSSStr(curComponent.styles))
    // }
  }, [curComponent])

  if (!curComponentId || !curComponent) return null;

  function renderFormElememt(setting: ComponentSetter) {
    const { type, options } = setting;
  
    if (type === 'select') {
      return <Select options={options} />
    } else if (type === 'input') {
      return <Input />
    } else if (type === 'inputNumber') {
        return <InputNumber />
    }
  }

  function valueChange(changeValues: CSSProperties) {
    if (curComponentId) {
        updateComponentStyles(curComponentId, changeValues);
    }
  }
    
    //加个debounce
    const handleEditorChange = debounce((value) => {
        setCss(value);
    
        const css: Record<string, string> = {};
    
        try {
            const cssStr = value.replace(/\/\*.*\*\//, '') // 去掉注释 /** */
                .replace(/(\.?[^{]+{)/, '') // 去掉 .comp {
                .replace('}', '');// 去掉 }
    
            styleToObject(cssStr, (name, value) => {
                css[name.replace(/-\w/, (item) => item.toUpperCase().replace('-', ''))] = value;
            });
    
            console.log(css);
            // updateComponentStyles(curComponentId, css);
            updateComponentStyles(curComponentId, {...form.getFieldsValue(), ...css}, true);

        } catch(e) {
            console.error('CSS解析错误:', e);
        }
    }, 500);

    function toCSSStr(css: Record<string, any>) {
        let str = `.comp {\n`;
        for(const key in css) {
            let value = css[key];
            if(!value) {
                continue;
            }
            if(['width', 'height'].includes(key) &&  !value.toString().endsWith('px')) {
                value += 'px';
            }

            str += `\t${key}: ${value};\n`
        }
        str += `}`;
        return str;
    }


  return (
    <Form
      form={form}
      onValuesChange={valueChange}
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 14 }}
    >
      {
        componentConfig[curComponent.name]?.stylesSetter?.map(setter => (
          <Form.Item key={setter.name} name={setter.name} label={setter.label}>
            {renderFormElememt(setter)}
          </Form.Item>
        ))
      }
          <div className='h-[200px] border-[1px] border-[#ccc]'>
              <CssEditor 
                  value={css}
                  onChange={handleEditorChange}
              />
          </div>

    </Form>
  )
}
